let timestamp = 0; // 最后请求时间
let requestLoop = []; // 合并请求

// 弹窗列表
const popup_list = [
    // 支付时，显示切换货币的弹窗
    "payment_switching_currency",
    // 1小时内支付超过3次
    "payment_switching_batchtip",
];

const state = () => ({
    name: "",
    collect: "",
    company: "",
    contact_email: "",
    country_iso_name: "",
    country_name: "",
    email: "",
    email_subscribe: 0,
    is_sub: true,
    level: "",
    oauth_type: 0,
    phone: "",
    model_tag: "hanging",
    size_type: 0,
    discount: 100, // 等级折扣
    popup_flags: 0, // 弹窗显示
    show_wallet: 0, // 是否显示钱包组件  0 1 不显示，2显示
    is_wallet: 0, // 否开通钱包支付 0 1 未开通，2开通
});

const getters = {
    // 裁片
    getUserInfo(state) {
        return state || {};
    },
    // 获取权限
    getPopupAccess(state) {
        const result = {};
        popup_list.map((item, index) => {
            const value = Math.pow(2, index);
            const access = (state.popup_flags & value) === value;
            result[item] = access;
        });
        return result;
    },
};

const mutations = {
    // 设置用户信息
    SET_USER_INFO(state, info) {
        const user = info || {};
        Object.keys(info).map((key) => {
            if (key == "level") {
                //    等级的不管
            } else {
                state[key] = user[key];
            }
        });
    },
    SET_USER_LEVEL(state, payload) {
        const option = payload || {};
        const level = parseInt(option.level);
        const discount = parseInt(option.discount);

        if (isNaN(level) || level > 7 || level < 1) {
            // 有问题的等级
        } else if (state.level != level) {
            state.level = level;
            state.discount = discount || 100;
            if (process.client) {
                // 客户端，清空一些缓存
                window.CACHE_PRODUCT_LIST = null;
            }
        }
    },
    DEL_USER_INFO(state, info) {
        Object.keys(state).map((key) => {
            if (Number.isFinite(state[key])) {
                state[key] = 0;
            } else if (
                Object.prototype.toString.call(state[key]) == "[object String]"
            ) {
                state[key] = "";
            } else {
                state[key] = null;
            }
        });
    },

    SET_ACCESS(state, payload) {
        const access = payload.access;
        const allow = payload.allow;
        const index = popup_list.indexOf(access);
        if (allow) {
            state.popup_flags = state.popup_flags | Math.pow(2, index);
        } else {
            state.popup_flags = state.popup_flags & ~Math.pow(2, index);
        }
    },
};
const actions = {
    // 设置用户信息
    setUserInfo(store, payload) {
        // TODO
        // ----------------------------------------
        // payload.currency = store.state.currency
        // payload.popup_flags = 0;
        const option = payload || {};
        const change = Object.keys(option).filter(
            (key) => store.state[key] !== option[key]
        );

        if (change.length > 0) {
            store.commit("SET_USER_INFO", option);
            store.commit("SET_USER_LEVEL", option);
        }

        store.rootState.currency = option.sales_territory;
        store.rootState.rate = option.rate;

        // console.log(store.state);
    },

    removeUserInfo(store, payload) {
        store.commit("DEL_USER_INFO");
    },

    // 更新弹窗权限
    async updatePopupAccess(store, payload) {
        const name = (payload || {}).name;
        const close = (payload || {}).close;
        const state = !close && close != 0 ? 1 : close ? 1 : 2;
        const index = popup_list.indexOf(name);

        if (index < 0) {
            // 没有这个key
        } else {
            const code = Math.pow(2, index);
            const res = await this.$http("User.setPopupFlags/" + code, {
                state: state,
            });
            if (res.code == 0) {
                store.state.popup_flags = res.data;
            }
        }
    },

    // 获取用户数据
    async updateUserInfo(store, payload) {
        const isLogin = !!store.rootState.token;
        const source = (payload || {}).source || "";
        const force = (payload || {}).force;

        if (!process.client) {
            // 不是客户端不允许访问
        } else if (!isLogin) {
            // 未登录
            store.dispatch("removeUserInfo");
        } else {
            // 不用变更
            const nowtime = new Date().getTime();
            if (force || source == "token" || nowtime - timestamp > 300000) {
                // 强制更新或是获取时间
                return await new Promise((resolve, reject) => {
                    if (requestLoop.length > 0) {
                        requestLoop.push({ resolve: resolve, reject: reject });
                    } else {
                        requestLoop.push({ resolve: resolve, reject: reject });
                        this.$http("getUserInfo", { source: source }).then(
                            (res) => {
                                if (res.code == 0) {
                                    store.dispatch("setUserInfo", res.data);
                                    timestamp = nowtime;
                                    requestLoop.map((obj) =>
                                        obj.resolve(res.data)
                                    );
                                    requestLoop.length = 0;
                                } else {
                                    requestLoop.map((obj) => obj.reject());
                                    requestLoop.length = 0;
                                }
                            }
                        );
                    }
                });
            }
        }
    },
};

export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions,
};
